<template>
	<om-page :title="pageTitle">
		<view class="om_hd_fix">
			<uni-search-bar 
			bgColorCls="bg-steelblue" 
			cancelColor="text-white"
			 :focus="focus" 
			 :placeholder="placeholder" 
			 @cancel="cancel"
			 @confirm="confirm" 
			 ></uni-search-bar>
		</view>
		<view class="page__bd" style="padding-top: 100rpx;"></view>
		<scroll-view :scroll-y="true" style="max-height: 250px;" class="scroll-Y">
			<view class="flex padding">
				<view class="tui-col-6 align-center flex">{{'已选中['+selectNameList.length+']'}}</view>
				<view class="tui-col-6 tui-right"> 
					<button v-if="showAllSelectBtn && showAll" type="primary" style="margin-right: 15px;" size="mini" @click="selectAll">全选</button>
					<button v-if="showAllSelectBtn && !showAll" type="primary" style="margin-right: 15px;" size="mini" @click="clearAll">取消</button>
					<button type="primary" size="mini" @click="confirmSelect">完成</button>
				</view>
			</view>
			<ot-input-tags id="ot-input-tags-id" class="bg-white" placeholder="选中项展示区" @change="changeTags" :selectlist='selectNameList' disabled></ot-input-tags>
		</scroll-view>
		<om-divider :gap="[0, 0]"></om-divider>
		<view v-show="showData">
			<checkbox-group v-if="commonData.datas" style="padding-left: 15px">
				<view style="display: flex; flex-flow:row wrap;">
					<label v-for="(item, index) in commonData.datas" :key="index" style="width:100%;border-bottom:1px solid #eee8e9 ;" @click="itemtap(item)">
						<view class="institution-dataList" >
							<view class="" >
								<checkbox
								 class='blue'
								 :class="item.checked?'checked':''"
								 :disabled="false"
								 :checked="item.checked"/>
							</view>
							<view v-if="item[namefield]" class="institution-name">
								<view class="" :style="{'max-width':(url?630:330)+'rpx'}" style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
									{{  getName(item) }}
								</view>
							</view>
							<view v-if="item[namefield]" class="institution-name">
								<view class="" :style="{'max-width':(url?630:330)+'rpx'}" style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
									{{  getNote(item) }}
								</view>
							</view>
						</view>
					</label>
				</view>
			</checkbox-group>
		  </view>
		  <tui-loadmore :visible="commonData.loadding"></tui-loadmore>
		  <tui-nomore :visible="!commonData.pullUpOn"></tui-nomore>
		  <tui-scroll-top :scrollTop="scrollTop" style="background: rgba(124, 174, 255, 0.5)"></tui-scroll-top>
	  </view>
	</om-page>
</template>

<script>
	import listLoad from '../../../static/js/listLoad.js';
	import { hasValue,changeTreeData} from '@/static/js/formUtil.js';
	const app = getApp()
	export default {
		data() {
			return {
				scrollViewHeight: 250,
				scrollTop: 0,
				searchStr:"",
				commonData: {
					datas:[]
				},
				pageTitle:"搜索",
				placeholder:"关键字查找",
				selectNameList:[],//字符串数组
				selectItemList:[],//选中的项目列表
				method:'get',//url对应的服务器方法的请求类型
				cachename:'',//缓存名称（必有）
				url:'',//服务器路径（必有）
				namefield: "dicname",//保证正确，显示属性,列标题
				namesplit:"|",//间隔符
				notefield: "",//保证正确，显示属性，列副标题
				notesplit:"|",//间隔符
				extrafield: "",//保证正确，显示属性，列右侧提示
				extrasplit:"|",//间隔符
				maxSelectNum:0,//选择的最大个数
				userMaxSelectTip:'',
				searchfield: "searchStr",//查询属性
				pagination: false,
				initdataList:[],//加载本地数据
				other: {},//其他查询属性
				initload: false,
				focus:false,
				showAllSelectBtn:false,
				showAll:true,
				showData:true,
				sign:'',
				key:'id',
				key2:'',
				mark:'' // 唯一标识
			}
		},
		computed: {
			getHeightStyler() {
				return `height:${this.scrollViewHeight}px;`;
			},
			maxSelectTip(){
				return this.userMaxSelectTip || `超过了约束的最大个数${this.maxSelectNum}`;
			}
		},
		watch: {
		　　'commonData.datas':{
				handler(newValue, oldValue){
					if(!this.pagination && this.initdataList.length == 0 && newValue.length){
						this.initdataList = newValue
					}
				},
				deep:true
			}
		},
		created: function () {
		  this.initData = this._.debounce(this.initData, 300)
		},
		methods: {
			getSelectList(){
				let _that = this
				uni.getStorage({
					key: _that.cachename,
					success: function(res) {
						_that.selectNameList = res.data.map((e,i)=>{
							let flag = false
							for(let item of _that.commonData.datas){
								if(e[_that.key] == item[_that.key]){
									flag = true
									_that.$set(item,'checked',true)
									_that.selectItemList.push(item)
									return {title: item[_that.namefield]}
								}
							}
							if(!flag){
								_that.selectItemList.push(res.data[i])
								return {
									title: res.data[i][_that.namefield]
								}
							}
						})
						uni.removeStorage({
							key: _that.cachename
						});
					}
				});
				_that.selectItemList.map(e=>{
					for(let item of _that.commonData.datas){
						if(e[_that.namefield] == item[_that.namefield]){
							_that.$set(item,'checked',true)
						}
					}
				})
			},
			getSelectNameList(){
				let _that = this
				uni.getStorage({
					key: _that.cachename,
					success: function(res) {
						let arr = res.data
						_that.selectNameList = arr.map(e=>{
							for(let item of _that.commonData.datas){
								if(item[_that.sign] == e[_that.sign]){
									_that.$set(item,'checked',true)
								}
							}
							_that.$set(e,'checked',true)
							_that.selectItemList.push(e)
							return {title: e[_that.namefield]}
						})
						_that.showAll = !_that.showAll
						uni.removeStorage({
							key: _that.cachename
						});
					}
				});
			},
			cancel(){
				this.commonData.datas = []
			},
			clearAll(){
				let _that = this
				this.selectNameList = []
				this.selectItemList = []
				_that.showAll = !_that.showAll
				for(let item of _that.commonData.datas){
					_that.$set(item,'checked',false)
				}
			},
			selectAll(){
				let _that = this  
				var selectNames = this.selectNameList.map(e=>e.title)
				for(let item of _that.commonData.datas){
					_that.$set(item,'checked',true)
					if(!selectNames.includes(item[this.namefield])){
						_that.$set(item,'checked',true)
						_that.selectNameList.push({title:item[this.namefield]})
						_that.selectItemList.push(item)
					}
				}
				_that.showAll = !_that.showAll
			},
			calcBgColor(item){
				var selectNames = this.selectNameList.map(e=>e.title)
				if(selectNames.includes(item[this.namefield])){
					return 'olive light'
				}else{
					return ''
				}
			},
			confirm(e){
				let _that = this;
				if (e && e.value) {
				  if (!this.searchStr || (this.searchStr && this.searchStr != e.value.trim())) {
					this.searchStr = e.value.trim()
					_that.initData()
				  }
				}else{
					this.searchStr = ''
					if(this.initload){
						_that.initData()
					}else{
						uni.getStorage({
							key: _that.cachename,
							success: function(res) {
								let arr = res.data
								_that.selectNameList = arr.map(e=>{
										_that.selectItemList.push(e)
										_that.$set(e,'checked',true)
										return {title: e[_that.namefield]}
								})
								_that.showAll = !_that.showAll
								uni.removeStorage({
									key: _that.cachename
								});
							}
						});
						this.commonData.datas= []
					}
				}
			},
			initData(){
				let _that = this
				let query = {}
				Object.assign(query, _that.other)
				query[_that.searchfield] = _that.searchStr
				if(_that.searchfield){
					query[_that.searchfield] = _that.searchStr
				}
				if(_that.pagination) {
					listLoad.initData(_that,_that.url,query).then(res=>{
						_that.getSelectList()
					})
				} else {
					if(_that.initdataList.length){
						var arr = []
						if(_that.likefield){
							arr = _that.likefield.split("|")
						}
						if(_that.namefield){
							arr = [...arr, _that.namefield.split(_that.namesplit)]
						}
						if(_that.notefield){
							arr = [...arr, _that.notefield.split(_that.notesplit)]
						}
						if(_that.extrafield){
							arr = [...arr, _that.extrafield.split(_that.extrasplit)]
						}
						var datas = _that.initdataList.filter(re=>{
							if(_that.searchStr){
								for(var i=0; i<arr.length; i++){
									if(~re[arr[i]].indexOf(_that.searchStr)){
										return true
									}
								}
								return false
							}else{
								return _that.initload
							}
						})
						if(!_that.showData){
							_that.showData = true
						}
						_that.commonData.datas = datas
					} else {
						if(!_that.loaded){
							_that.loaded = true
							listLoad.initData(_that,_that.url,query).then(res=>{
								_that.commonData.datas = [...changeTreeData(_that.commonData.datas)]
								_that.initdataList =  _that.commonData.datas
								uni.getStorage({
									key: _that.cachename,
									success: function(r) {
										_that.selectNameList = r.data.map(e=>{
											for(let item of _that.commonData.datas){
												if(e[_that.key] && e[_that.key] == item[_that.key]){
													if(_that.key2){
														if(e[_that.key2] && e[_that.key2] == item[_that.key2]){
															_that.$set(item,'checked',true)
															_that.selectItemList.push(item)
															return {title: item[_that.namefield]}
														}
													}else{
														if(e[_that.key] && e[_that.key] == item[_that.key]){
															_that.$set(item,'checked',true)
															_that.selectItemList.push(item)
															return {title: item[_that.namefield]}
														}
													}
												}
												if(e.code && e.code == item.code){
													_that.$set(item,'checked',true)
													_that.selectItemList.push(item)
													return {title: item[_that.namefield]}
												}
											}
										})
										_that.showAll = !_that.showAll
										uni.removeStorage({
											key: _that.cachename
										});
									}
								});
							})
							
						}
					}
				}
			},
			searchClear() {
				this.commonData = {}
			},
			verifySelectNum:function(){
				if(this.maxSelectNum  && this.selectItemList.length >= this.maxSelectNum){
					this.om.toast(this.maxSelectTip);
					return false;
				}else{
					return true;
				}
			},
			itemtap: function(item) {
				if(!this.verifySelectNum()){
					return
				}
				if(this.mark){
					if(this.selectItemList.length == 0){ 
						this.selectNameList.push({title:item[this.namefield]})
						this.selectItemList.push(item)
						this.$set(item,'checked',true)
					}else{
						for(let index in this.selectItemList){
							if(this.selectItemList[index][this.mark] == item[this.mark]){
								this.changeTags([],index)
								this.$set(item,'checked',false)
							}else{
								if(!item.checked){
									this.selectNameList.push({title:item[this.namefield]})
									this.selectItemList.push(item)
									this.$set(item,'checked',true)
								}
							}
						}
					}
				}else{
					var selectNames = this.selectNameList.map(e=>e.title)
					if(selectNames.includes(item[this.namefield])){
						var index = this._.indexOf(selectNames,item[this.namefield])
						this.changeTags([],index)
						this.$set(item,'checked',false)
					}else{
						this.selectNameList.push({title:item[this.namefield]})
						this.selectItemList.push(item)
						this.$set(item,'checked',true)
					}
				}
			},
			//删除时，index有值
			changeTags(selectList, index){
				if(hasValue(index)){
					if((!selectList || !selectList.length) && this.selectNameList.length){
						this.selectNameList.splice(index, 1);
					}
					this.selectItemList.splice(index, 1);
				}
				
				let unselectItemList = _.difference(this.commonData.datas, this.selectItemList);
				for(let i=0; i<this.selectItemList.length;i++){
					this.$set(this.selectItemList[i],'checked',true)
				}
				for(let i=0; i<unselectItemList.length;i++){
					this.$set(unselectItemList[i],'checked',false)
				}
			},
			confirmSelect(){
				uni.setStorage({
				   key: this.cachename,
				   data: this.selectItemList
				})
				//回主页面
				uni.navigateBack();
			},
			 getName(item){
				var s = ""
				if(this.namefield){
					var arr = this.namefield.split(this.namesplit)
					if(arr.length){
						arr.forEach(e => {
							if(item[e] != null && item[e] != undefined){
								if(s){
									s += " " + this.namesplit + " " + item[e]
								} else {
									s += item[e]
								}
							}
						})
					}
				}
				return s
			 },
			 getNote(item){
				var s = ""
				if(this.notefield){
					var arr = this.notefield.split(this.notesplit)
					if(arr.length){
						arr.forEach(e => {
							if(item[e] != null && item[e] != undefined){
								if(s){
									s += " " + this.notesplit + " " + item[e]
								} else {
									s += item[e]
								}
							}
						})
					}
				}
				return s
			 },
			 getExtra(item){
				var s = ""
				if(this.extrafield){
					var arr = this.extrafield.split(this.extrasplit)
					if(arr.length){
						arr.forEach(e => {
							if(item[e] != null && item[e] != undefined){
								if(s){
									s += " " + this.extrasplit + " " + item[e]
								} else {
									s += item[e]
								}
							}
						})
					}
				}
				return s
			 }
		},
		onLoad(options) {
			let _that = this
			this.pageTitle = options.title||"搜索"
			uni.setNavigationBarTitle({
			  title: this.pageTitle
			})
			if(!options.cachename){//缓存名称
				uni.navigateBack()
			}
			this.cachename = options.cachename
			if(!options.url){//搜索路径
				if(options.initdata){//初始数据，无需通过url加载
					this.commonData.datas = JSON.parse(options.initdata)
				}else{
					uni.navigateBack()
				}
			}
			this.url = options.url
			if(options.initload){//数据是否初始加载
				this.initload = true
			}
			if(options.namefield){//列标题字段
				this.namefield = options.namefield
			}
			if(options.searchfield){//查询字段
				this.searchfield = options.searchfield
			}
			if(options.notefield){//加载对象列表的显示属性
				this.notefield = options.notefield
			}
			if(options.extrafield){//加载对象列表的显示属性
				this.extrafield = options.extrafield
			}
			if(options.method){//加载对象列表的显示属性
				this.method = options.method
			}
			if(options.pagination){//是否分页
				this.pagination = true
			}
			if(options.placeholder){//搜索提示
				this.placeholder = options.placeholder
			}
			if(options.other){//其他查询参数
				var json = JSON.parse(options.other);
				for(var j in json){
					if(hasValue(json[j])){
						this.other[j] = json[j];
					}
				}
			}
			
			if(options.namesplit){//间隔符
				this.namesplit = options.namesplit
			}
			if(options.notesplit){//间隔符
				this.notesplit = options.notesplit
			}
			if(options.extrasplit){//间隔符
				this.extrasplit = options.extrasplit
			}
			if(options.showAllSelectBtn){
				this.showAllSelectBtn = options.showAllSelectBtn
			}
			if(options.maxSelectNum){
				this.maxSelectNum = options.maxSelectNum
			}
			if(options.showData == "false"){
				this.showData = false
			}
			if(options.userMaxSelectTip){
				this.userMaxSelectTip = options.userMaxSelectTip
			}
			if(options.sign){
				this.sign = options.sign
			}
			if(options.key){
				this.key = options.key
			}
			if(options.key2){
				this.key2 = options.key2
			}
			if(options.mark){
				this.mark = options.mark
			}
			if(!options.initdata){//初始备选数据
				this.confirm()
			}else{
				this.getSelectNameList()
			}
			this.$nextTick(function(){
				_that.focus = false
				// _that.focus = true
				// uni.hideKeyboard()
			})
		}, 
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
		},
		//页面相关事件处理函数--监听用户下拉动作
		onPullDownRefresh: function() {
			listLoad.pullDownRefresh(this)
		},
		// 页面上拉触底事件的处理函数
		onReachBottom: function() {
			if(this.pagination){
				listLoad.reachBottomReturn(this).then(res=>{
					this.commonData.loadding = false
					this.getSelectList()
				})
			}else{
				this.commonData.pullUpOn = false
			}
		}
	}
</script>

<style>
.scroll-Y {
	/* top: 0; */
	/* position: fixed; */
	z-index: 10;
	background-color: white;
	box-shadow: 0 1px 10px #929191; /*for Android*/
	-webkit-box-shadow: 0px 1px 10px #b3b2b2; /*for IOS*/
}
	.institution-dataList{
		height:100rpx;
		display: flex; 
		flex-direction:row; 
		align-items: center;
	}
	.institution-name{
		font-size:32rpx; margin: 10px;
	}

</style>
